﻿using System.Configuration;
using System.Net.Configuration;
using System.Net.Mail;
using System.Web;
using System.Web.Configuration;
using CultivJupiterContactForm.Model;

namespace CultivJupiterContactForm.Classes
{
    internal class Email
    {
        public void Send(Contact contact)
        {
            var config = WebConfigurationManager.OpenWebConfiguration(HttpContext.Current.Request.ApplicationPath);
            var settings = (MailSettingsSectionGroup)config.GetSectionGroup("system.net/mailSettings");
            if(settings == null || settings.Smtp.From == null || settings.Smtp.From == string.Empty)
                throw new ConfigurationErrorsException("No system.net/mailSettings section found or settings/mailSettings/smtp from address is empty");

            var mail = new MailMessage(
                 string.Format("{0} <{1}>", contact.Name, contact.From),
                 settings.Smtp.From,
                 string.Format(contact.Subject, contact.Name),
                 contact.Message);

            new SmtpClient().Send(mail);
        }
    }
}